import pymongo
from datetime import datetime
import redis
client = pymongo.MongoClient('mongodb://cs_user:cmcc5188@localhost:12018/cs_recharge')
conn = redis.Redis(db=0)
db = client.cs_recharge
now = datetime.now()
date = now.strftime("%Y%m%d")
order_coll = db.rechange
mer_coll = db.merchant

merchants = mer_coll.find({"merchant_type": "话费方"})

res = order_coll.aggregate([{"$match": {"orderdate": date, "orderstate": "0"}}, {"$group": {"_id": {"merchantid": "$merchantid", "amount": "$amount"}, "count": {"$sum": 1}}}])
balance_dict = {}
for merchant in merchants:
    balance_dict[merchant['merchantid']] = 0

for item in res:
    balance_dict[item['_id']["merchantid"]] += int(item['_id']['amount']) * item['count']

for merchantid, amount in balance_dict.items():
    # res = order_coll.find({"merchantid": merchant['merchantid'], "orderstate": "0", "orderdate": date})

    line_credit = conn.hget(merchantid, 'lineCredit')
    discounts = conn.hget(merchantid, 'discounts')
    if line_credit and discounts:
        line_credit = float(line_credit.decode())
        discounts = float(discounts.decode())
        balance = line_credit - (amount * discounts)
        conn.hset(merchantid, 'balance', balance)

